package org.jiamandan.com.strategy.impl.charge.device;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jiamandan.com.constant.ChargeConstant;
import org.jiamandan.com.constant.JSYConstant;
import org.jiamandan.com.dto.OrderDto;
import org.jiamandan.com.strategy.IChargeBaseService;
import org.springframework.stereotype.Service;


@Service(value = ChargeConstant.Service.JSY_SERVICE)
@AllArgsConstructor
@Slf4j
public class JsyChargeListener extends IChargeBaseService {

    @Override
    public void issueCharge(OrderDto orderDto, Channel channel) throws Exception {
        log.info("嘉满电-JSY下发充电设备号【" +orderDto.getPileNo() + "】充电时长（分钟）：" + orderDto.getMaxChargeTime() + "，最大功率：" + orderDto.getMaxPower());
            StringBuilder builder = new StringBuilder();
            builder.append("_" + JSYConstant.Cmd.S00201).append("/0027:");
            builder.append(orderDto.getGunNo() + "/")
                    .append(StringUtils.leftPad(StrUtil.toString(orderDto.getMaxChargeTime()), 4, "0"))
                    .append("/")
                    .append(StringUtils.leftPad(Long.toHexString(Long.valueOf(orderDto.getTradeNo())), 16, "0"))
                    .append("/02") //刷卡01或者服务器命令02
                    .append("\r\n");
            log.info("嘉满电-JSY下发充电(CMD=S00201)设备号【" + orderDto.getPileNo() + "】报文:" + builder.toString());
            ByteBuf buf = Unpooled.buffer(builder.toString().getBytes().length);
            buf.writeBytes(builder.toString().getBytes());
            ChannelFuture future = channel.writeAndFlush(buf);
            log.info(JSON.toJSONString(future));
    }

}
